from django.http import Http404, HttpResponseRedirect
from lib.decorators import render_to
from framework.models import *
from django.views.decorators.cache import cache_page
import re, datetime

@cache_page(24 * 60 * 60)
@render_to('homepage.html')
def homepage(request):
    return { 'table': Placement.get_table(),
             'countries': Country.all() }

@cache_page(24 * 60 * 60)
@render_to('iframe.html')
def test(request, id):
    placement = Placement.get_by_id(int(id))
    if placement == None:
        raise Http404('No placements matches the given query.')

    return { 'placement': placement,
             'id': id }
             
def save(request):
    country = db.GqlQuery("select * from Country where code2 = :1", request.POST['country'])
    browser = db.GqlQuery("select * from Browser where name = :1", request.POST['browser'])
    uid = datetime.datetime.now()
    
    if (country.count() == 0 or browser.count() == 0):
        raise Http404('Wrong input data.')
        
    
    for res in request.POST['scores'].split(';'):
        [id, time] = res.split('=')
        placement = Placement.get_by_id(int(id))
        if placement != None:
            score = Score(placement = placement,
                          score = int(time),
                          browser = browser[0],
                          country = country[0],
                          version = request.POST['version'],
                          uid = uid)
            score.put()
        
    return HttpResponseRedirect("/report/")

@render_to('debug.html')
def report(request):
    return {}